//
//  FontData.swift
//  
//
//  Created by 孙长坦 on 2022/6/17.
//

import Foundation
import UIKit

public struct FontData: Codable {
    private static let fontWeights: [String: UIFont.Weight] = [
        "normal": .regular,
        "regular": .regular,
        "medium": .medium,
        "bold": .bold,
    ]
    
    public let fontName: String?
    
    public let fontSize: CGFloat
    
    public let fontWeight: CGFloat?
    
    public init(fontName: String? = nil,
                fontSize: CGFloat,
                fontWeight: CGFloat? = nil) {
        self.fontName = fontName
        self.fontSize = fontSize
        self.fontWeight = fontWeight
    }
    
    public init(from decoder: Decoder) throws {
        do {
            let container = try decoder.singleValueContainer()
            fontSize = try container.decode(CGFloat.self)
            
            fontName = nil
            fontWeight = nil
        } catch {
            let container = try decoder.container(keyedBy: CodingKeys.self)
                
            fontName = try? container.decodeIfPresent(String.self, forKey: .fontName)
            
            fontSize = try container.decode(CGFloat.self, forKey: .fontSize)
            
            if let fontWeight = try? container.decodeIfPresent(CGFloat.self, forKey: .fontWeight) {
                self.fontWeight = fontWeight
            } else if let fontWeight = try? container.decodeIfPresent(String.self, forKey: .fontWeight) {
                self.fontWeight = FontData.fontWeights[fontWeight, default: .regular].rawValue
            } else {
                fontWeight = nil
            }
        }
    }
}

